﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace myShop
{
    public partial class FMSHOP : Form
    {
        public int iAction=0;
        public string stablename = string.Empty;
        public string sBusidate1 = string.Empty;
        public string sBusidate2 = string.Empty;
        string sStoreId = string.Empty;
        LogFile Log = new LogFile();
        OracleHelper myOracle = new OracleHelper();
        MysqlConnector myMysql = new MysqlConnector();

        private void doGetStore()
        {
            try
            {
                string SQL = "select storeid,storechinesename from store where 1=1";
                Log.doWriteLog(1, SQL);
                DataTable myTable = myOracle.query(SQL);
                if (!(myTable is null) && myTable.Rows.Count == 0)
                {
                    doAddLog("门店编号无法获取");
                    return;
                }

                sStoreId = myTable.Rows[0][0].ToString();
                Log.doWriteLog(1, "门店编号:" + sStoreId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("门店编号错误:" + ex.Message);
                doAddLog("门店编号错误:" + ex.Message);
            }
        }

        private void doAddLog(string sMsg)
        {
            richTextBox1.AppendText(DateTime.Now.ToString("HH:mm:ss") +"->"+ sMsg + Environment.NewLine);
        }

        //循环每行每个字段产生语句
        private void doExport(string sTable,string sField,string sDBName)
        {
            //访问oracle  
            try
            {
                string SQL = string.Empty;

                //读取字段
                doAddLog("  读取字段");

                SQL = "select column_name,data_type from user_tab_columns"
                 + " where table_name = '" + sTable.ToUpper() + "'"
                 + " order by column_id";
                //Log.doWriteLog(1, SQL);
                DataTable myTable = myOracle.query(SQL);
                if (!(myTable is null) && myTable.Rows.Count == 0)
                {
                    doAddLog("  表不存在");
                    return;
                }

                //检查是否有storeid 字段 store_cost 没有storeid字段
                Boolean iStore = false;

                //检查是否是storenumber字段 posul_alipay_detail
                Boolean iStoreNumber = false;

                //字段列表
                string sInset = "";
                for (int i = 0; i < myTable.Rows.Count; i++)
                {
                    //Console.WriteLine(myTable.Rows[i][0].ToString());
                    sInset = sInset + "," + myTable.Rows[i][0].ToString();
                    if (myTable.Rows[i][0].ToString().ToLower() == "storeid")
                    {
                        iStore = true;
                    }
                    if (myTable.Rows[i][0].ToString().ToLower() == "storenumber")
                    {
                        iStoreNumber = true;
                    }
                }

                if (iStore)
                {
                    sInset = "insert into " + sDBName + sTable.ToLower()
                       + "(" + sInset.Substring(1, sInset.Length - 1) + ")";
                }
                else
                {
                    if (iStoreNumber)//没有storenumber 才需要添加storeid
                    {
                        sInset = "insert into " + sDBName + sTable.ToLower()
                           + "(" + sInset.Substring(1, sInset.Length - 1) + ")";
                    }
                    else
                    {
                        sInset = "insert into " + sDBName + sTable.ToLower()
                           + "(" + sInset.Substring(1, sInset.Length - 1) + ",storeid)";
                    }
                }

                //读取数据
                string sValue = " values";
                string sRecord = string.Empty;

                doAddLog("  读取数据");
                SQL = "select * from " + sTable.ToLower()
                 + " where 1=1 ";
                if (iStore)
                {
                   SQL = SQL  +" and storeid='" + sStoreId + "'";
                }
                if (iStoreNumber)
                {
                    SQL = SQL + " and storenumber='" + sStoreId + "'";
                }

                if (sField !="")
                {
                    // Set title bar to selected date.
                    SQL = SQL + " and " + sField + " between to_date('" + sBusidate1 + "','yyyy-mm-dd')"
                     + " and to_date('" + sBusidate2 + "  23:59:59','yyyy-mm-dd hh24:mi:ss')";
                }
                Log.doWriteLog(1, SQL);
                DataTable myData = myOracle.query(SQL);
                if (!(myData is null) && myData.Rows.Count == 0)
                {
                    doAddLog("  没有数据");
                    return;
                }

                //组织数据
                for (int j = 0; j < myData.Rows.Count; j++)
                {
                    sRecord = "";
                    for (int i = 0; i < myTable.Rows.Count; i++) 
                    {
                        string _FieldName = myTable.Rows[i][0].ToString();
                        if (myTable.Rows[i][1].ToString() == "DATE")
                        {
                            if ((myData.Rows[j][_FieldName].ToString().Length==0)|| (myData.Rows[j][_FieldName].ToString() == ""))
                            {
                                sRecord = sRecord + ",null";
                            }
                            else
                            {
                                sRecord = sRecord + ",DATE_FORMAT('" + myData.Rows[j][_FieldName].ToString() + "','%Y-%m-%d %H:%i:%s')";
                            }
                            
                        }
                        else if (myTable.Rows[i][1].ToString() == "NUMBER")
                        {
                            if ((myData.Rows[j][_FieldName].ToString().Length == 0) || (myData.Rows[j][_FieldName].ToString() == ""))
                            {
                                sRecord = sRecord + ",0";
                            }
                            else
                            {
                                sRecord = sRecord + "," + myData.Rows[j][_FieldName].ToString() ;
                            }
                        }
                        else
                        {
                            sRecord = sRecord + ",'" + myData.Rows[j][_FieldName].ToString() + "'";
                        }
                    }
                    
                    sRecord = sRecord.Substring(1, sRecord.Length - 1);
                    if (j == 0)
                    {
                        if (iStore)
                        {
                            sValue = sValue + "(" + sRecord + ")";
                        }
                        else
                        {
                            if (!iStoreNumber)//没有storenumber 才需要添加storeid
                            {
                                sValue = sValue + "(" + sRecord + ",'" + sStoreId + "'" + ")";
                            }
                            else
                            {
                                sValue = sValue + "(" + sRecord + ")";
                            }
                        }
                    }
                    else
                    {
                        if (iStore)
                        {
                            sValue = sValue + ",(" + sRecord + ")";
                        }
                        else
                        {
                            if (!iStoreNumber) //没有storenumber 才需要添加storeid
                            {
                                sValue = sValue + ",(" + sRecord + ",'" + sStoreId + "'" + ")";
                            }
                            else
                            {
                                sValue = sValue + ",(" + sRecord + ")";
                            }
                        }
                    }
                }
                doAddLog("  数据判断");
                sValue = sValue + ";";

                //
                string sBefore = string.Empty;
                if (radioButton1.Checked)
                {
                    sBefore = "delete from  " + sDBName + sTable.ToLower()
                        + " where 1=1";
                    if (iStoreNumber)
                    {
                        sBefore = sBefore + " and storenumber='" + sStoreId + "'";
                    }
                    else
                    {
                        sBefore = sBefore + " and storeid='" + sStoreId + "'";
                    }
                }
                else
                {
                    //检查是否有数据，有数据删除
                    SQL = "select 1 from " + sDBName + sTable.ToLower()
                      + " where 1=1 ";
                    if (iStoreNumber)
                    {
                        SQL = SQL + " and storenumber='" + sStoreId + "'";
                    }
                    else
                    {
                        SQL = SQL + " and storeid='" + sStoreId + "'";
                    }
                    SQL = SQL  + " and " + sField + " between '" + sBusidate1 + "'"
                      + " and '"+sBusidate2+ "  23:59:59'"
                      + " limit 1 ";
                    DataTable myRecord = myMysql.query(SQL);
                    if (!(myRecord is null) && myRecord.Rows.Count > 0)
                    {
                        sBefore = "delete from  " + sDBName + sTable.ToLower()
                           + " where 1=1";
                        if (iStoreNumber)
                        {
                            sBefore = sBefore + " and storenumber='" + sStoreId + "'";
                        }
                        else
                        {
                            sBefore = sBefore + " and storeid='" + sStoreId + "'";
                        }
                        sBefore = sBefore + " and " + sField + " between '" + sBusidate1 + "'"
                           + " and '" + sBusidate2 + "  23:59:59'";
                    }
                }
                List<String> SQLStringList = new List<string>();
                
                if (sBefore.Length > 0)
                {
                    //Log.doWriteLog(1, sBefore);
                    SQLStringList.Add(sBefore);
                }
                
                //Log.doWriteLog(1, sInset + sValue);
                SQLStringList.Add(sInset + sValue);

                //执行
                //doAddLog("  保存数据");
                int iCount = myMysql.ExecuteSqlTran(SQLStringList);
                Console.WriteLine("保存笔数:" + iCount.ToString());
                doAddLog("  保存笔数:" + iCount.ToString());
                Log.doWriteLog(1, sTable+"保存笔数: " + iCount.ToString());
                SQLStringList.Clear();

            }
            catch (Exception ex)
            {
                Console.WriteLine("执行报错:" + ex.Message);
                doAddLog("执行报错:" + ex.Message);
            }
        }

        //直接产生语句
        private void doExport2(string sTable, string sField, string sDBName)
        {
            //访问oracle  
            try
            {
                string SQL = string.Empty;

                //读取字段
                doAddLog("  读取字段");

                SQL = "select column_name,data_type from user_tab_columns"
                 + " where table_name = '" + sTable.ToUpper() + "'"
                 + " order by column_id";
                //Log.doWriteLog(1, SQL);
                DataTable myTable = myOracle.query(SQL);
                if (!(myTable is null) && myTable.Rows.Count == 0)
                {
                    doAddLog("  表不存在");
                    return;
                }

                //检查是否有storeid 字段 store_cost 没有storeid字段
                Boolean iStore = false;

                //检查是否是storenumber字段 posul_alipay_detail
                Boolean iStoreNumber = false;

                //字段列表
                string sInset = "";
                string sSelec = "";
                for (int i = 0; i < myTable.Rows.Count; i++)
                {
                    //Console.WriteLine(myTable.Rows[i][0].ToString());
                    string sFieldName = myTable.Rows[i][0].ToString();
                    sInset = sInset + "," + myTable.Rows[i][0].ToString();
                    if (myTable.Rows[i][0].ToString().ToLower() == "storeid")
                    {
                        iStore = true;
                    }
                    if (myTable.Rows[i][0].ToString().ToLower() == "storenumber")
                    {
                        iStoreNumber = true;
                    }

                    if (myTable.Rows[i][1].ToString() == "DATE")
                    {
                        if (i == 0)
                        {
                            sSelec = sSelec + "''''" + "||NVL(to_char(" + sFieldName + ", 'yyyy-mm-dd hh24:mi:ss'),'1970-07-07')||" + "''''" + "||','||";
                        }
                        else
                        {
                            sSelec = sSelec + "''''" + "||NVL(to_char(" + sFieldName + ", 'yyyy-mm-dd hh24:mi:ss'),'1970-07-07')||" + "''''" + "||','||";
                        }
                    }
                    else if (myTable.Rows[i][1].ToString() == "NUMBER")
                    {
                        sSelec = sSelec +"NVL("+ sFieldName + ",0)||','||";
                    }
                    else
                    {
                        if (i == 0)
                        {
                            sSelec = sSelec + "'''''" + "||" + sFieldName + "||" + "''''" + "||','||";
                        }
                        else
                        {
                            sSelec = sSelec + "''''" + "||" + sFieldName + "||" + "''''" + "||','||";
                        }
                    }

                }

                if (iStore)
                {
                    sInset = "insert into " + sDBName + sTable.ToLower()
                       + "(" + sInset.Substring(1, sInset.Length - 1) + ")";

                    sSelec = sSelec.Substring(1, sSelec.Length - 8);
                }
                else
                {
                    if (iStoreNumber)//没有storenumber 才需要添加storeid
                    {
                        sInset = "insert into " + sDBName + sTable.ToLower()
                           + "(" + sInset.Substring(1, sInset.Length - 1) + ")";
                        sSelec = sSelec.Substring(1, sSelec.Length - 8);
                    }
                    else
                    {
                        sInset = "insert into " + sDBName + sTable.ToLower()
                           + "(" + sInset.Substring(1, sInset.Length - 1) + ",storeid)";

                        sSelec = sSelec + "''''||'"+ sStoreId+ "'||''''";
                    }
                }

                //doAddLog(sSelec);

                //读取数据
                doAddLog("  读取数据");
                SQL = "select "+ sSelec+" from " + sTable.ToLower()
                 + " where 1=1 ";
                if (iStore)
                {
                    SQL = SQL + " and storeid='" + sStoreId + "'";
                }
                if (iStoreNumber)
                {
                    SQL = SQL + " and storenumber='" + sStoreId + "'";
                }

                if (sField != "")
                {
                    // Set title bar to selected date.
                    SQL = SQL + " and " + sField + " between to_date('" + sBusidate1 + "','yyyy-mm-dd')"
                     + " and to_date('" + sBusidate2 + "  23:59:59','yyyy-mm-dd hh24:mi:ss')";
                }
                //Log.doWriteLog(1, SQL);
                DataTable myData = myOracle.query(SQL);
                if (!(myData is null) && myData.Rows.Count == 0)
                {
                    doAddLog("  没有数据");
                    return;
                }

                //组织数据
                string oldStr = "'1970-07-07'";
                string newStr = "null";
                string sValue = "values";
                for (int j = 0; j < myData.Rows.Count; j++)
                {
                    string str = myData.Rows[j][0].ToString();
                    str = str.Replace(oldStr, newStr);
                    if (j == 0){
                        sValue = sValue + "(" + str + ")";
                    }
                    else
                    {
                        sValue = sValue + ",(" + str + ")";
                    }
                }
                doAddLog("  数据判断");
                sValue = sValue + ";";

                //
                string sBefore = string.Empty;
                if (radioButton1.Checked)
                {
                    sBefore = "delete from  " + sDBName + sTable.ToLower()
                        + " where 1=1";
                    if (iStoreNumber)
                    {
                        sBefore = sBefore + " and storenumber='" + sStoreId + "'";
                    }
                    else
                    {
                        sBefore = sBefore + " and storeid='" + sStoreId + "'";
                    }
                }
                else
                {
                    //检查是否有数据，有数据删除
                    SQL = "select 1 from " + sDBName + sTable.ToLower()
                      + " where 1=1 ";
                    if (iStoreNumber)
                    {
                        SQL = SQL + " and storenumber='" + sStoreId + "'";
                    }
                    else
                    {
                        SQL = SQL + " and storeid='" + sStoreId + "'";
                    }
                    SQL = SQL + " and " + sField + " between '" + sBusidate1 + "'"
                      + " and '" + sBusidate2 + "  23:59:59'"
                      + " limit 1 ";
                    DataTable myRecord = myMysql.query(SQL);
                    if (!(myRecord is null) && myRecord.Rows.Count > 0)
                    {
                        sBefore = "delete from  " + sDBName + sTable.ToLower()
                           + " where 1=1";
                        if (iStoreNumber)
                        {
                            sBefore = sBefore + " and storenumber='" + sStoreId + "'";
                        }
                        else
                        {
                            sBefore = sBefore + " and storeid='" + sStoreId + "'";
                        }
                        sBefore = sBefore + " and " + sField + " between '" + sBusidate1 + "'"
                           + " and '" + sBusidate2 + "  23:59:59'";
                    }
                }
                List<String> SQLStringList = new List<string>();

                if (sBefore.Length > 0)
                {
                    //Log.doWriteLog(1, sBefore);
                    SQLStringList.Add(sBefore);
                }

                //Log.doWriteLog(1, sInset + sValue);
                SQLStringList.Add(sInset + sValue);

                //执行
                //doAddLog("  保存数据");
                int iCount = myMysql.ExecuteSqlTran(SQLStringList);
                Console.WriteLine("保存笔数:" + iCount.ToString());
                doAddLog("  保存笔数:" + iCount.ToString());
                Log.doWriteLog(1, sTable + "保存笔数: " + iCount.ToString());
                SQLStringList.Clear();

            }
            catch (Exception ex)
            {
                Console.WriteLine("执行报错:" + ex.Message);
                doAddLog("执行报错:" + ex.Message);
            }
        }

        //用过程导出数据
        private void doExport3(string sTable, string sField, string sDBName)
        {
            //访问oracle  
            try
            {
                string SQL = string.Empty;

                //读取字段
                doAddLog("  读取字段");

                SQL = "select column_name,data_type from user_tab_columns"
                 + " where table_name = '" + sTable.ToUpper() + "'"
                 + " order by column_id";
                DataTable myTable = myOracle.query(SQL);
                if (!(myTable is null) && myTable.Rows.Count == 0)
                {
                    doAddLog("  表不存在");
                    return;
                }

                //检查是否有storeid 字段 store_cost 没有storeid字段
                Boolean iStore = false;

                //检查是否是storenumber字段 posul_alipay_detail
                Boolean iStoreNumber = false;

                //字段列表
                string sInset = "";
                string sSelec = "";
                for (int i = 0; i < myTable.Rows.Count; i++)
                {
                    //Console.WriteLine(myTable.Rows[i][0].ToString());
                    string sFieldName = myTable.Rows[i][0].ToString();
                    sInset = sInset + ",`" + myTable.Rows[i][0].ToString()+ "`";
                    if (myTable.Rows[i][0].ToString().ToLower() == "storeid")
                    {
                        iStore = true;
                    }
                    if (myTable.Rows[i][0].ToString().ToLower() == "storenumber")
                    {
                        iStoreNumber = true;
                    }

                    if (myTable.Rows[i][1].ToString() == "DATE")
                    {
                        if (i == 0)
                        {
                            sSelec = sSelec + "'''''" + "||NVL(to_char(" + sFieldName + ", 'yyyy-mm-dd hh24:mi:ss'),'1970-07-07')||" + "''''" + "||','||";
                        }
                        else
                        {
                            sSelec = sSelec + "''''" + "||NVL(to_char(" + sFieldName + ", 'yyyy-mm-dd hh24:mi:ss'),'1970-07-07')||" + "''''" + "||','||";
                        }
                    }
                    else if (myTable.Rows[i][1].ToString() == "NUMBER")
                    {
                        sSelec = sSelec + " NVL(" + sFieldName + ",0)||','||";
                    }
                    else
                    {
                        if (i == 0)
                        {
                            sSelec = sSelec + "'''''" + "||" + sFieldName + "||" + "''''" + "||','||";
                        }
                        else
                        {
                            sSelec = sSelec + "''''" + "||" + sFieldName + "||" + "''''" + "||','||";
                        }
                    }

                }

                if (iStore)
                {
                    sInset = "insert into " + sDBName + sTable.ToLower()
                       + "(" + sInset.Substring(1, sInset.Length - 1) + ")";

                    sSelec = sSelec.Substring(1, sSelec.Length - 8);
                }
                else
                {
                    if (iStoreNumber)//没有storenumber 才需要添加storeid
                    {
                        sInset = "insert into " + sDBName + sTable.ToLower()
                           + "(" + sInset.Substring(1, sInset.Length - 1) + ")";
                        sSelec = sSelec.Substring(1, sSelec.Length - 8);
                    }
                    else
                    {
                        sInset = "insert into " + sDBName + sTable.ToLower()
                           + "(" + sInset.Substring(1, sInset.Length - 1) + ",storeid)";

                        sSelec = sSelec.Substring(1, sSelec.Length - 1);//导入表没有storeid，导入语句不正确
                        sSelec = sSelec + "''''||'" + sStoreId + "'||''''";
                    }
                }
                //doAddLog(sSelec);

                //读取数据:塞入临时表，在从临时表导出
                doAddLog("  读取数据");

                string sTemp = "E" + sTable.ToUpper();
                SQL = "select table_name"
                 + " from user_tab_comments "
                 + " where table_name = '"+ sTemp+"'";
                myTable = myOracle.query(SQL);
                if (!(myTable is null) && myTable.Rows.Count > 0)
                {
                    SQL = "drop table " + sTemp;
                    myOracle.doExec(SQL);
                }

                SQL = "create table "+sTemp 
                 +" as "
                 +" select " + sSelec + " f from " + sTable.ToLower()
                 +" where 1=1 ";
                if (iStore)
                {
                    SQL = SQL + " and storeid='" + sStoreId + "'";
                }
                if (iStoreNumber)
                {
                    SQL = SQL + " and storenumber='" + sStoreId + "'";
                }

                if (sField != "")
                {
                    // Set title bar to selected date.
                    SQL = SQL + " and " + sField + " between to_date('" + sBusidate1 + "','yyyy-mm-dd')"
                     + " and to_date('" + sBusidate2 + "  23:59:59','yyyy-mm-dd hh24:mi:ss')";
                }
                myOracle.doExec(SQL);

                SQL = "select count(1) from "+ sTemp;
                DataTable myData = myOracle.query(SQL);
                if (!(myData is null) && myData.Rows.Count == 0)
                {
                    doAddLog("  没有数据");
                    return;
                }

                doAddLog("  导出数据");

                string path = System.Environment.CurrentDirectory + "\\exp";
                if (!Directory.Exists(path))//判断是否存在
                {
                    Directory.CreateDirectory(path);//创建新路径
                }
                SQL = "select * from "+sTemp+" where 1=1";
                string sFile = sTable.ToLower()+".csv";
                //doAddLog(path);
                //SQL = "call sql_to_csv('select f from exp_employee where 1=1','d:\','employee.csv');";
                myOracle.doSQL_TO_CSV(SQL,path,sFile);

                //组织数据
                sFile = path + "\\" + sFile;
                if (!File.Exists(sFile))
                {
                    doAddLog("  文件不存在" + sFile);
                    return;
                }

                doAddLog("  组织数据");
                string oldStr = "'1970-07-07'";
                string newStr = "null";
                string sValue = "values";
                try
                {
                    // 读取文本文件
                    string line = ReadTxtFile(sFile);

                    if (line.Length<10)
                    {
                        doAddLog("  查询不到符合条件的数据");
                        return;
                    }

                    sValue = sValue + line.Replace(oldStr, newStr);
                    //using (StreamReader sr = new StreamReader(sFile))
                    //{
                    //    string line;
                    //    // ReadLine()一行一行的循环读取
                    //    //当然可以直接ReadToEnd()读到最后
                    //    while ((line = sr.ReadLine()) != null)
                    //    {
                    //        //Console.WriteLine(line);
                    //        line = line.Replace(oldStr, newStr);
                    //        sValue = sValue + line;
                    //    }
                    //}
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                doAddLog("  数据判断");
                sValue = sValue + ";";

                //
                string sBefore = string.Empty;
                if (radioButton1.Checked)
                {
                    sBefore = "delete from  " + sDBName + sTable.ToLower()
                        + " where 1=1";
                    if (iStoreNumber)
                    {
                        sBefore = sBefore + " and storenumber='" + sStoreId + "'";
                    }
                    else
                    {
                        sBefore = sBefore + " and storeid='" + sStoreId + "'";
                    }
                }
                else
                {
                    //检查是否有数据，有数据删除
                    SQL = "select 1 from " + sDBName + sTable.ToLower()
                      + " where 1=1 ";
                    if (iStoreNumber)
                    {
                        SQL = SQL + " and storenumber='" + sStoreId + "'";
                    }
                    else
                    {
                        SQL = SQL + " and storeid='" + sStoreId + "'";
                    }
                    SQL = SQL + " and " + sField + " between '" + sBusidate1 + "'"
                      + " and '" + sBusidate2 + "  23:59:59'"
                      + " limit 1 ";
                    DataTable myRecord = myMysql.query(SQL);
                    if (!(myRecord is null) && myRecord.Rows.Count > 0)
                    {
                        sBefore = "delete from  " + sDBName + sTable.ToLower()
                           + " where 1=1";
                        if (iStoreNumber)
                        {
                            sBefore = sBefore + " and storenumber='" + sStoreId + "'";
                        }
                        else
                        {
                            sBefore = sBefore + " and storeid='" + sStoreId + "'";
                        }
                        sBefore = sBefore + " and " + sField + " between '" + sBusidate1 + "'"
                           + " and '" + sBusidate2 + "  23:59:59'";
                    }
                }
                List<String> SQLStringList = new List<string>();

                if (sBefore.Length > 0)
                {
                    //Log.doWriteLog(1, sBefore);
                    SQLStringList.Add(sBefore);
                }

                //Log.doWriteLog(1, sInset + sValue);
                SQLStringList.Add(sInset + sValue);

                //执行
                //doAddLog("  保存数据");
                int iCount = myMysql.ExecuteSqlTran(SQLStringList);
                Console.WriteLine("保存笔数:" + iCount.ToString());
                doAddLog("  保存笔数:" + iCount.ToString());
                Log.doWriteLog(1, sTable + "保存笔数: " + iCount.ToString());
                SQLStringList.Clear();

                //2023.08.03 调用过程 方便特殊处理
                SQL = "CALL proc_input('"+ sTable + "','"+ sStoreId+"');";
                doAddLog("  特殊处理:" + SQL);
                myMysql.ExeUpdate(SQL);

            }
            catch (Exception ex)
            {
                Console.WriteLine("执行报错:" + ex.Message);
                doAddLog("执行报错:" + ex.Message);
            }
        }

        //读取超大文本文件
        //https://blog.csdn.net/txwtech/article/details/122449888
        private string ReadTxtFile(string fileName)
        {

            string txt = "";
            // var fileDir = this.txtFileFolder.Text.Trim();
            var fileDir = fileName;

            byte[] allBytes = null;

            byte[] buffer = new byte[1024];//一个1K的缓冲字节容器
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Restart();
            using (MemoryStream ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(fileDir, FileMode.Open, FileAccess.Read))
                {
                    int positon = 0;
                    while ((positon = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, positon);

                    }

                    allBytes = ms.ToArray();
                }

            }
            stopwatch.Stop();
            // MessageBox.Show($"StreamReader StreamWriter 程序运行花费的时间:{(double)stopwatch.ElapsedMilliseconds / 1000:0.000} secs");

            if (null != allBytes)
            {
                //尝试将字节转成字符串
                //txt = System.Text.Encoding.UTF8.GetString(allBytes);

                txt = System.Text.Encoding.Default.GetString(allBytes);

            }
            string[] txtToArray = txt.Split('\r');
            //  ReadData_List.Add(txtToArray);
            return txt;

        }

        public FMSHOP()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化
            string sFile = Application.StartupPath + @"\MP10.ssk";
            if (File.Exists(sFile))
            {
                skinEngine1.SkinFile = sFile;
            }
            Log.doWriteLog(1, "启动程序");

            string sVersion = "(版本:" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + ")";
            this.Text = this.Text + sVersion;
            //sTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //listBox1.Items.Add(sTime + ":" + Global.sTIME .ToString()+ "分钟后启动");

            tabControl1.SelectedIndex = 0;
            // Initialize picker to yesterday.
            //2023.05.08 当天
            DateTime result = DateTime.Today.Subtract(TimeSpan.FromDays(0));
            dateTimePicker1.Value = result;
            dateTimePicker2.Value = result;

            dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.PaleTurquoise;      //奇數列顏色

            //先建立個 CheckBox 欄
            DataGridViewCheckBoxColumn cbCol = new DataGridViewCheckBoxColumn();
            cbCol.Width = 85;   //設定寬度
            cbCol.HeaderText = "    全选";
            cbCol.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;   //置中
            dataGridView1.Columns.Insert(0, cbCol);

            #region 建立全选 CheckBox

            //建立個矩形，等下計算 CheckBox 嵌入 GridView 的位置
            Rectangle rect = dataGridView1.GetCellDisplayRectangle(0, -1, true);
            rect.X = rect.Location.X + rect.Width / 3 - 9;
            rect.Y = rect.Location.Y + (rect.Height / 2 - 9);

            rect.X = 8;
            rect.Y = panel2.Left;

            CheckBox cbHeader = new CheckBox();
            cbHeader.Name = "checkboxHeader";
            cbHeader.Size = new Size(18, 18);
            cbHeader.Location = rect.Location;
            //全選要設定的事件
            cbHeader.CheckedChanged += new EventHandler(cbHeader_CheckedChanged);

            //將 CheckBox 加入到 dataGridView
            dataGridView1.Controls.Add(cbHeader);

            #endregion

            Global.doGetINI();

            textBox1.Text = Global.m_server;
            textBox2.Text = Global.m_port;
            textBox3.Text = Global.m_userid;
            textBox4.Text = Global.m_password;
            textBox5.Text = Global.m_database;

            textBox10.Text = Global.o_server;
            textBox9.Text = Global.o_port;
            textBox8.Text = Global.o_userid;
            textBox7.Text = Global.o_password;
            textBox6.Text = Global.o_database;

            //判断是否传参
            if ((iAction > 0)&&(stablename.Length>0)&&(sBusidate1.Length>0))
            {
                tabControl1.SelectedTab = tabControl1.TabPages[1];
                try
                {
                    dateTimePicker1.Value = DateTime.ParseExact(sBusidate1, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                    dateTimePicker2.Value = DateTime.ParseExact(sBusidate2, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                    dateTimePicker1.Visible = true;
                    dateTimePicker2.Visible = true;

                    radioButton2.Checked = true;

                    button2_Click(null, null);

                    cbHeader.Checked = true;

                    timer1.Enabled = true;

                }
                catch (Exception ex)
                {
                    Console.WriteLine("批执行报错:" + ex.Message);
                    doAddLog("批执行报错:" + ex.Message);
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (iAction == 0)
            {
                if (MessageBox.Show("确定导入吗 ?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    Console.WriteLine("取消");
                    return;
                }
            }

            richTextBox1.Clear();

            if ((sStoreId.Length == 0)||(sStoreId is null))
            {
                doGetStore();
            }

            DateTime result1 = dateTimePicker1.Value;
            sBusidate1 = result1.ToString("yyyy-MM-dd");

            DateTime result2 = dateTimePicker2.Value;
            sBusidate2 = result2.ToString("yyyy-MM-dd");
            if (radioButton2.Checked)
            {
                doAddLog("业务日期:"+sBusidate1+"--"+sBusidate2);
            }
            progressBar1.Visible = true;
            progressBar1.Maximum = this.dataGridView1.Rows.Count;
            progressBar1.Value = 0;
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
               //onsole.WriteLine("准备导出表:" + dataGridView1.Rows[i].Cells[0].Value);
                if (!(dataGridView1.Rows[i].Cells[0].Value is null) && dataGridView1.Rows[i].Cells[0].Value.ToString()== "True")
                {
                    string sTable = dataGridView1.Rows[i].Cells[1].Value.ToString();
                    string sField = dataGridView1.Rows[i].Cells[3].Value.ToString();
                    string sDBName = dataGridView1.Rows[i].Cells[4].Value.ToString();
                    Console.WriteLine("准备导出表:" + sTable);
                    doAddLog("准备导出表:" + sTable);

                    //导入自动判断
                    if (iAction > 0){
                        if (sField != "")
                        {
                            radioButton2.Checked = true;
                        }
                        else
                        {
                            radioButton1.Checked = true;
                        }
                    }

                    if (Global.i_exp.Equals("3"))
                    {
                        doExport3(sTable, sField, sDBName);
                    }
                    else if (Global.i_exp.Equals("2"))
                    {
                        doExport2(sTable, sField, sDBName);
                    }
                    else
                    {
                        doExport(sTable, sField, sDBName);
                    }
                    
                }
                progressBar1.Value = progressBar1.Value + 1; 
            }
            progressBar1.Visible = false;
            doAddLog("导出完毕");
            Log.doWriteLog(1,"导出完毕");

            if (iAction >0)
            {
                doAddLog("导出完毕自动关闭");
                Application.ExitThread();
            }
        }

        private void cbHeader_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in dataGridView1.Rows)
                dr.Cells[0].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
        }

        //确定 保存数据库连接参数
        private void button2_Click(object sender, EventArgs e)
        {
            //
            string str = System.Environment.CurrentDirectory + "\\eShop.ini";
            IniFile ini = new IniFile(str);
            ini.IniWriteValue("MYSQL", "SCHost", textBox1.Text);
            ini.IniWriteValue("MYSQL", "SCPort", textBox2.Text);
            ini.IniWriteValue("MYSQL", "SCUser", textBox3.Text);
            ini.IniWriteValue("MYSQL", "SCPWD",  textBox4.Text);
            ini.IniWriteValue("MYSQL", "ORA",    textBox5.Text);

            ini.IniWriteValue("DB", "SCHost", textBox10.Text);
            ini.IniWriteValue("DB", "SCPort", textBox9.Text);
            ini.IniWriteValue("DB", "SCUser", textBox8.Text);
            ini.IniWriteValue("DB", "SCPWD",  textBox7.Text);
            ini.IniWriteValue("DB", "ORA  ",  textBox6.Text);

            Global.doGetINI();

            tabControl1.SelectedTab = tabControl1.TabPages[1];

            doGetTable();
        }

       //载入需要处理的表
       private void doGetTable()
        {
            try
            {
                string SQL = string.Empty;
                
                if (radioButton1.Checked)
                {
                    SQL= "SELECT ftablename,ftablenote,ffield,fdbname "
                     + " FROM ts_tablelist"
                     +" WHERE ftype = 0";
                }
                else
                {
                    SQL = "SELECT ftablename,ftablenote,ffield,fdbname "
                     + " FROM ts_tablelist"
                     + " WHERE ftype = 1";                   
                }

                //自动导入
                if (stablename.Length > 0)
                {
                    SQL = "SELECT ftablename,ftablenote,ffield,fdbname "
                     + " FROM ts_tablelist"
                     + " WHERE 1 = 1";
                    string sWhere = string.Empty;
                    string[] strArray = stablename.Split(',');
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        sWhere = sWhere + "," + "'" + strArray[i] + "'";
                    }
                    SQL = SQL + " and ftablename in ('0'" + sWhere + ")";
                }

                DataTable myTable = myMysql.query(SQL);

                dataGridView1.DataSource = myTable;

                if (!(myTable is null) && myTable.Rows.Count > 0)
                {
                    dataGridView1.Columns[1].HeaderText = "表名";
                    dataGridView1.Columns[1].Width = 180;
                    dataGridView1.Columns[1].ReadOnly = true;

                    dataGridView1.Columns[2].HeaderText = "备注";
                    dataGridView1.Columns[2].Width = dataGridView1.Width-(180+85+15);
                    dataGridView1.Columns[2].ReadOnly = true;

                    dataGridView1.Columns[3].Visible=false;
                    dataGridView1.Columns[4].Visible = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("doGetTable报错:" + ex.Message);

                doAddLog("doGetTable报错:" + ex.Message);
            }
        }

        private void radioButton2_Click(object sender, EventArgs e)
        {
            dateTimePicker1.Visible = true;
            dateTimePicker2.Visible = true;
            doGetTable();
        }

        private void radioButton1_Click(object sender, EventArgs e)
        {
            dateTimePicker1.Visible = false;
            dateTimePicker2.Visible = false;
            doGetTable();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            doAddLog("马上开始");
            button3_Click(null, null);
        }
    }

}
